flyui.namespace("flyui.apps.byexpressionprofile");

flyui.apps.byexpressionprofile.CustomGeneFinderRenderer = function() {};
flyui.apps.byexpressionprofile.CustomGeneFinderRenderer.prototype = new flyui.genefinder.DefaultRenderer(); 

/**
 * @private
 * Render the results summary pane.
 * @param {String} query the user's query
 * @param {Number} count number of results found
 */
flyui.apps.byexpressionprofile.CustomGeneFinderRenderer.prototype._renderResultsSummary = function( query, count ) {
    var _context = "flyui.genefinder.DefaultRenderer.prototype._renderResultsSummary";
    try {
        
        if (query instanceof Array) {
            flyui.debug("found array query", _context);
            query = query.join(", ");
        }
        var content = "found ";
        content += count;
        content += " matching <em>D. melanogaster</em> gene";
        content += (count == 0 || count > 1) ? "s " : " ";
        content += "from <a href='http://flybase.org'>flybase.org</a> ("+flyui.flybase.provenance+") ...";
        this._resultsSummaryPane.innerHTML = content;
        
    } catch (e) {
        flyui.debug("caught "+e.name, ", "+e.message, _context);
        throw new flyui.UnexpectedException(_context, e);
    }   
};


/**
 * @class
 * @constructor
 */
flyui.apps.byexpressionprofile.Application = function() {
	
	var that = this;
	
	var flyatlasprofile = null;
	var genefinder = null;
    var flyatlas = null;
    var flyted = null;
    var bdgp = null;
	var flybasepub = null;
//    var limit = 10000;
	
	this.initQueryTable = function() {
	    /*
        <table>
            <thead>
                <tr><th>brain</th></tr>
            </thead>
            <tbody>
                <tr>
                    <td><select id="select_brain_change"><option value="any">any</option><option value="up">up</option><option value="down">down</option><option value="nochange">no change</option></select></td>
                </tr>
            </tbody>
        </table>
	     */
	     var content = "<table><thead><tr>";
	     for (var i=1;i<flyui.flyatlas.tissues.length;i++) {
	         var tissue = flyui.flyatlas.tissues[i];
	         content += "<th>"+tissue+"</th>";
	     }
	     content += "</tr></thead><tbody><tr>";
	     
         for (var i=1;i<flyui.flyatlas.tissues.length;i++) {
             var tissue = flyui.flyatlas.tissues[i];
             content += "<td><select id=\"select_"+tissue+"_change\"><option value=\"any\">any</option><option value=\"Up\">up</option><option selected=\"selected\" value=\"Down\">down</option><option value=\"None\">none</option></select></td>";
         }
	     content += "</tr></tbody></table>";
	     $("#queryTableContainer").html(content);
	}
	
	
	this.initFlyatlasProfile = function() {
	    var context = "flyui.apps.byexpressionprofile.Application.initFlyatlasProfile";
	    try {

            flyui.debug("instantiate a service for the flyatlas profile widget", context);
            var service = new flyui.flyatlas.Service();
            service.setEndpoint("../../../data/flyatlas");
            
            flyui.debug("instantiate a renderer for the batchgenefinder widget", context);
            var renderPane = $("#flyatlasProfileWidget");
            var renderer = new flyui.flyatlas.ProfileWidget.DefaultRenderer(); // default renderer
            renderer.setCanvas(renderPane);
            
            flyui.debug("instantiate a flyatlas profile widget", context);
            flyatlasprofile = new flyui.flyatlas.ProfileWidget(service, renderer);
	        
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
	}
		
    this.initGeneFinder = function() {
        try {
            // initialise genefinder widget
    
            flyui.info("instantiate a service for the genefinder widget");
            var service = new flyui.flybase.Service("../../../data/flybase");
            
            flyui.info("instantiate a renderer for the genefinder widget");
            var renderPane = document.getElementById("geneFinderWidget");
//            var renderer = new flyui.genefinder.DefaultRenderer(); // default renderer
            var renderer = new flyui.apps.byexpressionprofile.CustomGeneFinderRenderer();
            renderer.setCanvas(renderPane);
            
            flyui.info("instantiate a genefinder widget");
            genefinder = new flyui.genefinder.Widget(service, renderer);
            
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
    };

	this.initFlybasepub = function(){
		 try {
	        
            flyui.info("instantiate a service for the flybase publication widget");
            var service = new flyui.flybasepub.Service();
            service.setEndpoint("../../../data/flybase");
            
            flyui.info("instantiate a renderer for the flybase publication widget");
            var renderer = new flyui.flybasepub.PublicationWidget.SimpleRenderer(); 
            renderer.setCanvas($("#flybasepubPublicationWidget"));
            
            flyui.info("instantiate a flybase publication widget");
            flybasepub = new flyui.flybasepub.PublicationWidget(service, renderer);
            
        } catch (error) {
            flyui.apps.publicationmashup.handleError(error);
        }
	};
        
    // called by this.init
    
    this.initFlyatlas = function() {
        try {
            
            flyui.info("instantiate a service for the flyatlas widget");
            var service = new flyui.flyatlas.Service();
            service.setEndpoint("../../../data/flyatlas");
            
            flyui.info("instantiate a renderer for the flyatlas widget");
            var renderer = new flyui.flyatlas.Widget.DefaultRenderer(); 
            renderer.setCanvas($("#flyatlasWidget"));
            
            flyui.info("instantiate a flyatlas widget");
            flyatlas = new flyui.flyatlas.Widget(service, renderer);
            
        } catch (error) {
            flyui.apps.expressionmashup.handleError(error);
        }
    };
    
    // called by this.init
    
    this.initFlyted = function() {
        try {
            
            flyui.info("instantiate a service for the flyted image widget");
            var service = new flyui.flyted.Service("../../../data/flyted");
            
            flyui.info("instantiate a renderer for the flyted image widget");
            var renderPane = document.getElementById("flytedImageWidget");
//            var renderer = new CustomFlytedRenderer();
            var renderer = new flyui.flyted.ImageWidget.DefaultRenderer();
            renderer.setCanvas(renderPane);
            
            flyui.info("instantiate a flyted image widget");
            flyted = new flyui.flyted.ImageWidget(service, renderer);
            
        } catch (error) {
            flyui.apps.expressionmashup.handleError(error);
        }
    };
    
    // called by this.init
    
    this.initBdgp = function() {
        try {
            
            flyui.info("instantiate a service for the bdgp image widget");
            var service = new flyui.bdgp.Service("../../../data/bdgp");
            
            flyui.info("instantiate a renderer for the bdgp image widget");
            var renderPane = document.getElementById("bdgpImageWidget");
//            var renderer = new CustomBdgpRenderer();
//            var renderer = new flyui.bdgp.ImageWidget.DefaultRenderer();
            var renderer = new flyui.bdgp.ImageWidget.CompactRenderer();
            renderer.setCanvas(renderPane);
            
            flyui.info("instantiate a bdgp image widget");
            bdgp = new flyui.bdgp.ImageWidget(service, renderer);
            
        } catch (error) {
            flyui.apps.expressionmashup.handleError(error);
        }
    };
    
    this.init = function() {
        var context = "flyui.apps.byexpressionprofile.Application.init";
        try {
    		
    		var logReader = new YAHOO.widget.LogReader("logger");

            this.initQueryTable();
            this.initFlyatlasProfile();
            this.initGeneFinder();
            this.initFlyatlas();
            this.initFlyted();
            this.initBdgp();
            this.initFlybasepub();

            flyui.debug("hook form submission to widget call", context);
            YAHOO.util.Event.addListener("queryForm", "submit", this.onFormSubmitted);
            
            flyui.debug("add listener for results received event", context);
            flyatlasprofile.subscribe("RESULTSRECEIVED", this.onResultsReceived, null);
            
            // attach gene selection listener to genefinder
            genefinder.subscribe("GENESELECTED", this.onGeneSelected, null);

    		flyui.debug("application loaded, showing main pane", context);
    		$("#loadingPane").hide();
    		$("#applicationPane").show();
    		
    		that.initState();
    		
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
	};
	
	this.onFormSubmitted = function(event) {
        var context = "flyui.apps.byexpressionprofile.Application.onFormSubmitted";
        try {
            flyui.debug("form submitted", context);
            var profile = {};
            
            flyui.debug("build profile object", context);
            for (var i=1;i<flyui.flyatlas.tissues.length;i++) {
                var tissue = flyui.flyatlas.tissues[i];
                var selectid = "select_"+tissue+"_change";
                var select = document.getElementById(selectid);
                var value = select.value;
                flyui.debug("found value "+value+" for select "+selectid, context);
                profile[tissue] = value;
            }
            that.setQueryState(profile);
            
            var limit = document.getElementById("queryLimit").value;
            that.doQuery(profile, limit);
            
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
	    
	};

    this.doQuery = function(profile, limit) {
        var context = "flyui.apps.byexpressionprofile.Application.doQuery";
        try {
            $("#errorMessage")
               .hide()
               .html("this should never be visible");
            $("#geneFinderWidget").hide();
            $("#flyatlasWidget").hide();
            $("#flytedImageWidget").hide();
            $("#bdgpImageWidget").hide();

            flyui.debug("initiate request for probes and genes by profile", context);
            flyui.debug("limit: "+limit, context);
            flyatlasprofile.getProbesAndGenesByExpressionProfile(profile, limit);
            
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
    }

    this.setQueryState = function(profile) {
        var context = "flyui.apps.byexpressionprofile.Application.setQueryState";
        try {
            
            var statestring = "";
            for (var tissue in profile) {
                statestring += tissue + ":" + profile[tissue] + "|";
            }
            
            var url = new String(window.location.href);
            var term = url.indexOf("#");
            if (term > 0) {
                url = url.substring(0, term);
            }
            window.location.href = url + "#query=" + escape(statestring);
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
    };
    
    this.initState = function() {
        var context = "flyui.apps.byexpressionprofile.Application.initState";
        try {
    
            var url = new String(window.location.href);
            var qi = url.indexOf("#query=");
            
            if (qi > 0) {
                var end = url.length;
                var statestring = unescape(url.substring(qi+7,end));
                flyui.info("found query: "+statestring);
                var profile = {};
                var params = statestring.split("|");
                for (var i=0;i<params.length;i++) {
                    var param = params[i];
                    var vals = param.split(":");
                    if (vals[0].length > 0) {
                        profile[vals[0]] = vals[1];
                        var selectid = "select_"+vals[0]+"_change";
                        flyui.debug(selectid, context);
                        document.getElementById(selectid).value = vals[1];
                    }
                }
                var limit = document.getElementById("queryLimit").value;
                that.doQuery(profile, limit);
            }
            
        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
    };

    

    this.onResultsReceived = function(type, args) {
        try {
            flyui.debug("application: results received");
            var results = args[0];
            var flybaseids = results.genes;
            
            genefinder.findGenesByAnyNameBatch(flybaseids);
            $("#geneFinderWidget").show();

        } catch (error) {
            flyui.apps.byexpressionprofile.handleError(error);
        }
    };
    
    this.onGeneSelected = function(type, args) {
        try {
            var gene = args[0];
            flyui.info("gene selected: "+gene+" "+gene.flybaseID);
            flyatlas.getAssaysByGene(gene);
            flyted.findImagesByGene(gene);
            bdgp.findImagesByGene(gene);
            flybasepub.findPublicationsByGene(gene)
            $("#flyatlasWidget").show();
            $("#flytedImageWidget").show();
            $("#bdgpImageWidget").show();
//            that.setSelectionState(gene);
        } catch (error) {
            flyui.apps.expressionmashup.handleError(error);
        }
    };  
    	
	this.init();
};

flyui.apps.byexpressionprofile.handleError = function(error) {
    flyui.err(error.name+" :: "+error.message);
    $("#errorMessage")
       .html("an error has occurred, please see the log for more details")
       .show();
};
    

// on dom ready, instantiate application
YAHOO.util.Event.onDOMReady(function() {new flyui.apps.byexpressionprofile.Application();});